/**
 * Classe de gestion des reunions
* @author I.T. Works.
* @date 27/12/2011
* @version 1.0
*/
package org.itworks.biodev.gui.panels;

import java.awt.event.*;
import java.sql.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

import org.itworks.biodev.gui.*;
import org.itworks.biodev.model.*;
import org.itworks.helpers.*;
import org.itworks.helpers.gui.*;

public class MeetingsPanelView extends JPanel implements Observer {
	
	
	/* Observer constants */
	public static final int FILL_PARTICIPANTS_TABLE = 0;
	public static final int FILL_MEETINGS_TABLE = 1;
	
	private static final long serialVersionUID = 3924521482317669382L;
	
	private static MeetingsPanelView meetingsPanel = null;
	
	private MeetingsPanelControler controler;
	private MainWindowView parent = null;
	
	private javax.swing.JButton addNewParticipantButton;
    private javax.swing.JLabel beginDateLabel;
    private javax.swing.JTextField beginDateTextField;
    private javax.swing.JButton createNewMeetingButton;
    private javax.swing.JButton deleteParticipantButton;
    private javax.swing.JButton deleteSelectedMeetingsButton;
    private javax.swing.JLabel endDateLabel;
    private javax.swing.JTextField endDateTextField;
    private javax.swing.JButton filterByDateButton;
    private javax.swing.JScrollPane meetingsListScrollPane;
    private javax.swing.JTable meetingsListTable;
    private javax.swing.JLabel meetingsTitleLabel;
    private javax.swing.JLabel participantCustomersLabel;
    private javax.swing.JScrollPane participantsListScrollPane;
    private javax.swing.JTable participantsListTable;
	
    /**Constructeur de la classe */
	private MeetingsPanelView(MainWindowView parent, MeetingsPanelControler controler) {
		this.parent = parent;
		this.controler = controler;
		this.controler.getModel().addObserver(this);
		initComponents();
		initHandlers();
		
		controler.viewLoaded();
	}
	
	/**Agencement des onglets et boutons */
	private void initComponents() {

        meetingsTitleLabel = new javax.swing.JLabel();
        beginDateLabel = new javax.swing.JLabel();
        beginDateTextField = new javax.swing.JTextField();
        endDateLabel = new javax.swing.JLabel();
        endDateTextField = new javax.swing.JTextField();
        filterByDateButton = new javax.swing.JButton();
        createNewMeetingButton = new javax.swing.JButton();
        deleteSelectedMeetingsButton = new javax.swing.JButton();
        meetingsListScrollPane = new javax.swing.JScrollPane();
        meetingsListTable = new javax.swing.JTable();
        participantCustomersLabel = new javax.swing.JLabel();
        addNewParticipantButton = new javax.swing.JButton();
        deleteParticipantButton = new javax.swing.JButton();
        participantsListScrollPane = new javax.swing.JScrollPane();
        participantsListTable = new javax.swing.JTable();

        meetingsTitleLabel.setFont(new java.awt.Font("Trebuchet MS", 1, 18));
        meetingsTitleLabel.setText("Reunions");

        beginDateLabel.setText("Date de debut :");

        endDateLabel.setText("Date de fin :");

        filterByDateButton.setText("Filtrer");

        createNewMeetingButton.setText("Creer une reunion");

        deleteSelectedMeetingsButton.setText("Supprimer la selection");

        meetingsListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Identifiant", "Date", "Hote", "Modifier", "Annuler"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        meetingsListTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        meetingsListScrollPane.setViewportView(meetingsListTable);
        meetingsListTable.getColumnModel().getColumn(0).setMinWidth(100);
        meetingsListTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        meetingsListTable.getColumnModel().getColumn(0).setMaxWidth(100);

        participantCustomersLabel.setFont(new java.awt.Font("Trebuchet MS", 1, 14)); // NOI18N
        participantCustomersLabel.setText("Clients participants :");

        addNewParticipantButton.setText("Ajouter un participant");

        deleteParticipantButton.setText("Supprimer la selection");

        participantsListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Identifiant", "Nom", "Prenom", "Adresse", "Code postal", "Ville", "E-Mail", "Telephone", "Supprimer"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        meetingsListTable.setRowSelectionAllowed(true);
        participantsListScrollPane.setViewportView(participantsListTable);
        /**Agencement des onglets et boutons */
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(beginDateLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(beginDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(endDateLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(endDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(filterByDateButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 286, Short.MAX_VALUE)
                        .addComponent(createNewMeetingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(deleteSelectedMeetingsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addComponent(meetingsTitleLabel)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(participantCustomersLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 555, Short.MAX_VALUE)
                        .addComponent(addNewParticipantButton, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(deleteParticipantButton, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(participantsListScrollPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 1080, Short.MAX_VALUE)
                            .addComponent(meetingsListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1080, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(meetingsTitleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(beginDateLabel)
                    .addComponent(beginDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(endDateLabel)
                    .addComponent(endDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filterByDateButton)
                    .addComponent(deleteSelectedMeetingsButton)
                    .addComponent(createNewMeetingButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(meetingsListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(deleteParticipantButton)
                        .addComponent(addNewParticipantButton))
                    .addComponent(participantCustomersLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(participantsListScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }
	
	/** Gestion du comportement des boutons*/
	private void initHandlers() {
		this.createNewMeetingButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				controler.createNewMeetingButtonActionPerformed(actionEvent);
				
			}
			
		});
		
		this.deleteSelectedMeetingsButton.addActionListener(new ActionListener() {
			
			
			public void actionPerformed(ActionEvent actionEvent) {
				Vector<Integer> selectedIndexes = new Vector<Integer>();
				/* Pour chaque ligne */
				for(int i = 0; i < meetingsListTable.getRowCount(); i++) {
					/* Si la case est coch�e */
					if(meetingsListTable.getValueAt(i, 4).toString().equals("true")) {
						selectedIndexes.add(Integer.parseInt(meetingsListTable.getValueAt(i, 0).toString()));
					}
				}
				controler.deleteSelectedMeetingsButtonActionPerformed(actionEvent, selectedIndexes);
			}
		});
		
		this.meetingsListTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent listSelectionEvent) {
				// TODO Auto-generated method stub7
				
				try {
					Meeting selectedMeeting;
					int selectedRow = meetingsListTable.getSelectedRow();
					if(selectedRow > -1) {
						int selectedIndex = Integer.parseInt(meetingsListTable.getValueAt(selectedRow, 0).toString());
						if(selectedIndex > -1) {
							selectedMeeting = MeetingTable.getInstance().find(selectedIndex);

							controler.meetingsListTableValueChanged(listSelectionEvent, selectedMeeting);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		
		this.addNewParticipantButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				int selectedIndex = meetingsListTable.getSelectedRow();
				if(selectedIndex > -1) {
					// TODO Auto-generated method stub
					
					// R�cup�re le meeting courant
					Meeting m = controler.getModel().getMeetings().elementAt(meetingsListTable.getSelectedRow());
					
					controler.addNewParticipantButtonActionPerformed(actionEvent, m);
				} else {
					JOptionPane.showMessageDialog(null, "Veuillez selectionner une reunion", "Erreur", JOptionPane.ERROR_MESSAGE);
				}
				
			}
			
		});
		
		this.filterByDateButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				controler.filterDateButtonActionPerformed(actionEvent, beginDateTextField.getText(), endDateTextField.getText());
			}
			
		});

	}
	
	public static MeetingsPanelView getInstance(MainWindowView parent) {
		if(meetingsPanel == null) {
			meetingsPanel = new MeetingsPanelView(parent, new MeetingsPanelControler(new MeetingsPanelModel()));
		}
		return meetingsPanel;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable srcObject, Object object) {
		// TODO Auto-generated method stub
		MVCNotification notification = (MVCNotification)object;
		int reason = notification.getReason();
		
		switch(reason) {
		case FILL_MEETINGS_TABLE:
			// todo.
			try {
				fillMeetingsTable( (Vector<Meeting>)notification.getObject() );
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		
		case FILL_PARTICIPANTS_TABLE:
			try {
				fillParticipantsTable((Vector<Customer>) notification.getObject() );
			} catch(Exception e) {
				e.printStackTrace();
			}
			break;
		}
		
	}
	
	/**Methode permettant de remplir la table des reunions*/
	private void fillMeetingsTable(Vector<Meeting> meetings) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		DefaultTableModel model = new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Identifiant", "Date", "Hote", "Modifier", "Supprimer"
            }
        ) {
			
            /**
			 * 
			 */
			private static final long serialVersionUID = -758028855472131221L;
			
			Class[] types = new Class [] {
	                java.lang.String.class, java.lang.String.class, java.lang.String.class,  Boolean.class, Boolean.class
	            };

	            public Class getColumnClass(int columnIndex) {
	                return types [columnIndex];
	            }
	            
			boolean[] canEdit = new boolean [] {
                false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
	        
		};
		
		meetingsListTable.setModel(model);
		
		for(Meeting m : meetings) {
			Vector<Object> rowData = new Vector<Object>();
			rowData.add(m.getId()+"");
			rowData.add(m.getDateTime().toString());
			try {
				rowData.add(m.getHoster().toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			rowData.add("Modifier");
			rowData.add(new Boolean(false));
			new ButtonColumn(meetingsListTable, new AbstractAction() {

				/**
				 * 
				 */
				private static final long serialVersionUID = 5911305847353251182L;

				@Override
				public void actionPerformed(ActionEvent actionEvent) {
					// TODO Auto-generated method stub
					int selectedIndex = meetingsListTable.getSelectedRow();
					controler.buttonColumnMeetingsActionPerformed(actionEvent, selectedIndex);
					
				}
				
			}, 3);
			model.addRow(rowData);
		}
	}
	
	/**Remplissage de la table des participants*/
	private void fillParticipantsTable(Vector<Customer> participants) {
		
		DefaultTableModel model = new javax.swing.table.DefaultTableModel(
	            new Object [][] {

	            },
	            new String [] {
	                "Identifiant", "Nom", "Prenom", "Adresse", "Code postal", "Ville", "E-Mail", "Telephone", "Supprimer"
	            }
	        ) {
	            /**
				 * 
				 */
				private static final long serialVersionUID = -3274817806431716598L;
				Class[] types = new Class [] {
	                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,java.lang.Boolean.class
	            };
	            boolean[] canEdit = new boolean [] {
	                false, false, false, false, false, false, false, false, true
	            };

	            public Class getColumnClass(int columnIndex) {
	                return types [columnIndex];
	            }

	            public boolean isCellEditable(int rowIndex, int columnIndex) {
	                return canEdit [columnIndex];
	            }
	        };
	        
		 participantsListTable.setModel(model);
		 
		 for(Customer p : participants) {
			 Vector<Object> rowData = new Vector<Object>();
			 rowData.add(p.getId());
			 rowData.add(p.getLastName());
			 rowData.add(p.getFirstName());
			 rowData.add(p.getAddress());
			 rowData.add(p.getPostalCode());
			 rowData.add(p.getCity());
			 rowData.add(p.getMail());
			 rowData.add(p.getPhoneNumber());
			 rowData.add(new Boolean(false));
			 
			 model.addRow(rowData);
		 }
	}
}